import json

from constr_budgets.models import Modules, Project, Materials,Templates,Place,Record,Day
from django.http import JsonResponse
from django.views import View
from utils.Infinite import infinite
import datetime


# 模板行数据
class Modules_port(View):
    def get(self, request):
        data = Modules.objects.all().values()

        datalist = infinite(list(data))
        return JsonResponse({
            'code': 200,
            'message': '获取权限列表成功',
            'data': list(datalist)
        })

    def post(self, request):
        data = json.loads(request.body)
        isMaterials = data['is_materials']
        models_data = Modules.objects.filter(id=data['pid']).values()
        pid_list = [data['pid']]
        name_list = [data['name']]
        totalModule = ""

        def fn(li):
            for pi in li:
                pid_list.append(pi['pid'])
                name_list.append(data['name'])
                date = Modules.objects.filter(id=pi['pid']).values()
                fn(date)
            return pid_list

        fn(models_data)
        if isMaterials == True:
            totalModule = Modules.objects.create(
                name=data['name'],  # 权限名称
                level=data['level'],  # 权限等级
                pid=pid_list[0],
                template_id=data['models_id'],  # 模板列表
                predict_money=data['predict_money'],  # 预算、测算总金额
                unit=data['unit'],  # 单位
                predict_do=data['predict_do'],  # 预算、测算总工程量
                is_materials=data['is_materials']
            )
            for p in pid_list[:-1]:
                print(p)
                models_data = Modules.objects.filter(pid=p).values()  # 获取当前添加的同级数据
                fatherdata = 0  # 父级predict_do
                father_money = 0
                for mod in models_data:  # 循环
                    fatherdata += mod['predict_do']  # 将子级的 predict_do 相加
                    father_money += mod['predict_money']  # 将子级的 predict_money 相加
                Modules.objects.filter(id=p).update(predict_do=fatherdata,
                                                    predict_money=father_money)  # 更新给父级的predict_do,predict_money
        else:
            if pid_list[0] == 0:
                totalModule = Modules.objects.create(
                    name=data['name'],  # 权限名称
                    level=data['level'],  # 权限等级
                    pid=pid_list[0],
                    template_id=data['models_id'],  # 模板列表
                    predict_money=data['predict_money'],  # 预算、测算总金额
                )

            else:
                totalModule = Modules.objects.create(
                    name=data['name'],  # 权限名称
                    level=data['level'],  # 权限等级
                    pid=pid_list[0],
                    template_id=data['models_id'],  # 模板列表
                    predict_money=data['predict_money'],  # 预算、测算总金额
                    # unit=data['unit'],  # 单位
                    # predict_do=data['predict_do'],  # 预算、测算总工程量
                )
                for p in pid_list:
                    models_data = Modules.objects.filter(pid=p).values()  # 获取当前添加的同级数据
                    fatherdata = 0  # 父级predict_money
                    for mod in models_data:  # 循环
                        fatherdata += mod['predict_money']  # 将子级的 predict_money 相加
                    Modules.objects.filter(id=p).update(predict_money=fatherdata)  # 更新给父级的predict_money

        aimtemplate = []
        for i in Templates.objects.filter(modules=totalModule.id):
            aimplace = Place.objects.filter(template_id=i.id)
            for j in Project.objects.filter(templates_id=i.id):
                create_time = j.createTime
                start_day = datetime.datetime.strptime(str(create_time),"%Y-%m-%d").date()
                start_day = Day.objects.filter(time__gte =start_day)
                for m in start_day:
                    print(m.time)
                    for n in aimplace:
                        newRecord = Record.objects.create(money=0,num=0,day_id=m.id,project_id=j.id)
                        newRecord.modules.add(totalModule.id)
                        newRecord.place.add(n.id)
                        newRecord.save()

        # totalModule
        # except:
        #     return JsonResponse({"code": 400, "message": "参数类型错误"})

        return JsonResponse({
            'code': 200,
            'message': '添加权限成功'
        })

    def put(self, request):
        data = json.loads(request.body)
        isMaterials = data['is_materials']
        models_data = Modules.objects.filter(id=data['pid']).values()
        pid_list = [data['pid']]
        Modules.objects.filter(id=data['id']).update(name=data['name'], predict_money=data['predict_money'],
                                                     unit=data['unit'], predict_do=data['predict_do'])
        print(data)

        def fn(li):
            for pi in li:
                pid_list.append(pi['pid'])
                date = Modules.objects.filter(id=pi['pid']).values()
                fn(date)
            return pid_list

        fn(models_data)
        if isMaterials == True:
            for p in pid_list[:-1]:
                print(p)
                models_data = Modules.objects.filter(pid=p).values()  # 获取当前添加的同级数据
                fatherdata = 0  # 父级predict_do
                father_money = 0
                for mod in models_data:  # 循环
                    fatherdata += mod['predict_do']  # 将子级的 predict_do 相加
                    father_money += mod['predict_money']  # 将子级的 predict_money 相加
                Modules.objects.filter(id=p).update(predict_do=fatherdata,
                                                    predict_money=father_money)  # 更新给父级的predict_do,predict_money
        else:
            for p in pid_list[:-1]:
                print(p)
                models_data = Modules.objects.filter(pid=p).values()  # 获取当前添加的同级数据
                # fatherdata = 0  # 父级predict_do
                father_money = 0
                for mod in models_data:  # 循环
                    # fatherdata += mod['predict_do']  # 将子级的 predict_do 相加
                    father_money += mod['predict_money']  # 将子级的 predict_money 相加
                Modules.objects.filter(id=p).update(predict_money=father_money)  # 更新给父级的predict_do,predict_money
        return JsonResponse({
            'code': 200,
            "message": "修改字段信息成功"
        })

    def delete(self, request):

        data=json.loads(request.body)
        d=data['id']
        print(d)
        isMaterials=data['is_materials']
        models_data1 = Modules.objects.filter(id=d).values()
        models_data = Modules.objects.filter(id=models_data1[0]['pid']).values()
        pid_list = [models_data1[0]['pid']]

        def fn1(li):
            for pi in li:
                pid_list.append(pi['pid'])
                date = Modules.objects.filter(id=pi['pid']).values()
                fn1(date)
            return pid_list

        fn1(models_data)

        def fn(id):
            dd = Modules.objects.filter(pid=id).values()
            for dat in dd:
                Modules.objects.filter(id=dat['id']).delete()
                fn(dat['id'])
            return ''

        fn(d)
        Modules.objects.filter(id=d).delete()
        if isMaterials == 1:
            for p in pid_list[:-1]:
                models_data = Modules.objects.filter(pid=p).values()  # 获取当前添加的同级数据
                fatherdata = 0  # 父级predict_do
                father_money = 0
                for mod in models_data:  # 循环
                    fatherdata += mod['predict_do']  # 将子级的 predict_do 相加
                    father_money += mod['predict_money']  # 将子级的 predict_money 相加
                Modules.objects.filter(id=p).update(predict_do=fatherdata,
                                                    predict_money=father_money)  # 更新给父级的predict_do,predict_money
        else:
            for p in pid_list[:-1]:
                models_data = Modules.objects.filter(pid=p).values()  # 获取当前添加的同级数据
                father_money = 0
                for mod in models_data:  # 循环
                    father_money += mod['predict_money']  # 将子级的 predict_money 相加
                Modules.objects.filter(id=p).update(predict_money=father_money)  # 更新给父级的predict_do,predict_money
        return JsonResponse({
            'code': 200,
            "message": "删除字段信息成功"
        })
